package com.edu.hre.common.ajax;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.sql.pim.EmployeeDAOService;
import com.edu.hre.struts.form.pim.EmployeeForm;

/**
 * Servlet implementation class EmployeeAjax
 */
public class EmployeeAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private static final Logger logger = Logger.getLogger(EmployeeAjax.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private static final EmployeeDAOService employeeDAOService = BeanFinder.getBean(EmployeeDAOService.BEAN_NAME, EmployeeDAOService.class);
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EmployeeAjax() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");
		String text = request.getParameter("text"); 
		if(StringUtils.isBlank(text) || text.contains("'") || text.contains("\"")){
			return;
		}
		// text = new String(text.getBytes("ISO-8859-1"), "UTF-8");
		CommonUtils.println("AJAX search for keyword: " + text);
		List <EmployeeForm> lists = employeeDAOService.getAllEmpSuggestions(text);
		if(lists == null || lists.size() == 0){
			return;
		}
		String results = "";
		for(EmployeeForm tmp : lists){
			try {
				results += ";" + tmp.getFirstName().trim();
			} catch (Exception e) {
				CommonUtils.println(e.getMessage());
			}
		}
		results = results.replaceFirst(";", "");
		CommonUtils.println(results);
		response.getWriter().write(results);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
